<template>
  <common-layout title="库存管理" >
    <!-- 标题+操作按钮区 -->
    <template #header-buttons>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>
        <span>搜索</span>
      </el-button>
      <el-button  @click="resetSearch">
        <el-icon><Refresh /></el-icon>
        <span>重置</span>
      </el-button>
    </template>

    <!-- 搜索区域 -->
    <template #search-form>
      <el-form :model="searchForm" class="search-form" :inline="true">
        <el-form-item label="物料编码" style="width: 260px;">
          <el-input v-model="searchForm.materialCode" placeholder="请输入物料编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="物料名称" style="width: 260px;">
          <el-input v-model="searchForm.materialName" placeholder="请输入物料名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="仓库" style="width: 260px;">
          <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable>
            <el-option v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.warehouseName" :value="warehouse.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态" style="width: 260px;">
          <el-select v-model="searchForm.status" placeholder="请选择库存状态" clearable>
            <el-option label="正常" value="1"></el-option>
            <el-option label="预警" value="0"></el-option>
            <el-option label="超储" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>

    <!-- 数据区 -->
    <template #data-content>
      <!-- 库存预警提示 -->
      <el-alert v-if="alerts.length > 0" title="库存预警" type="warning" :closable="false" class="alert-warning">
        <div v-for="alert in alerts" :key="alert.id" class="alert-item">
          {{ alert.materialName }} ({{ alert.materialCode }}) 在 {{ alert.warehouseName }} 仓库库存不足，当前库存: {{ alert.currentStock }}，安全库存: {{ alert.safetyStock }}
        </div>
      </el-alert>

      <!-- 库存表格 -->
      <el-table v-loading="loading" :data="inventoryList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码" width="120"></el-table-column>
        <el-table-column prop="materialName" label="物料名称" width="180"></el-table-column>
        <el-table-column prop="warehouseName" label="仓库名称" width="120"></el-table-column>
        <el-table-column prop="currentStock" label="当前库存" width="100"></el-table-column>
        <el-table-column prop="safetyStock" label="安全库存" width="100"></el-table-column>
        <el-table-column prop="maxStock" label="最大库存" width="100"></el-table-column>
        <el-table-column prop="unit" label="单位" width="80"></el-table-column>
        <el-table-column prop="status" label="库存状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="danger">预警</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">正常</el-tag>
            <el-tag v-else type="warning">超储</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDetails(scope.row)">查看详情</el-button>
            <el-button type="warning" size="small" @click="viewTransactions(scope.row)">交易记录</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </template>
  </common-layout>

    <!-- 库存详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="库存详情" width="50%">
      <el-form :model="currentInventory" label-width="120px">
        <el-form-item label="物料编码">
          <span>{{ currentInventory.materialCode }}</span>
        </el-form-item>
        <el-form-item label="物料名称">
          <span>{{ currentInventory.materialName }}</span>
        </el-form-item>
        <el-form-item label="仓库名称">
          <span>{{ currentInventory.warehouseName }}</span>
        </el-form-item>
        <el-form-item label="当前库存">
          <span>{{ currentInventory.currentStock }}</span>
        </el-form-item>
        <el-form-item label="安全库存">
          <span>{{ currentInventory.safetyStock }}</span>
        </el-form-item>
        <el-form-item label="最大库存">
          <span>{{ currentInventory.maxStock }}</span>
        </el-form-item>
        <el-form-item label="单位">
          <span>{{ currentInventory.unit }}</span>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-tag v-if="currentInventory.status === 0" type="danger">预警</el-tag>
          <el-tag v-else-if="currentInventory.status === 1" type="success">正常</el-tag>
          <el-tag v-else type="warning">超储</el-tag>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ currentInventory.createdAt }}</span>
        </el-form-item>
        <el-form-item label="更新时间">
          <span>{{ currentInventory.updatedAt }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 交易记录弹窗 -->
    <el-dialog v-model="transactionDialogVisible" title="库存交易记录" width="70%">
      <el-table v-loading="transactionLoading" :data="transactions" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="transactionType" label="交易类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.transactionType === 1" type="success">入库</el-tag>
            <el-tag v-else type="danger">出库</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="100"></el-table-column>
        <el-table-column prop="totalAmount" label="金额" width="120"></el-table-column>
        <el-table-column prop="referenceNumber" label="参考单据号" width="150"></el-table-column>
        <el-table-column prop="transactionTime" label="交易时间" width="180"></el-table-column>
        <el-table-column prop="operator" label="操作员" width="100"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="transactionCurrentPage"
          v-model:page-size="transactionPageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="transactionTotal"
          @size-change="handleTransactionSizeChange"
          @current-change="handleTransactionCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="transactionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { getInventoryList, getInventoryAlerts, getInventoryTransactions, getInventoryById } from '../api/inventory'
import { getWarehouseList } from '../api/warehouse'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import CommonLayout from '../components/CommonLayout.vue'

// 搜索表单
const searchForm = reactive({
  materialCode: '',
  materialName: '',
  warehouseId: '',
  status: ''
})

// 库存列表数据
const inventoryList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 仓库列表
const warehouses = ref([])

// 库存预警
const alerts = ref([])

// 详情弹窗
const detailDialogVisible = ref(false)
const currentInventory = ref({})

// 交易记录弹窗
const transactionDialogVisible = ref(false)
const transactions = ref([])
const transactionTotal = ref(0)
const transactionCurrentPage = ref(1)
const transactionPageSize = ref(10)
const transactionLoading = ref(false)
const currentInventoryId = ref(0)

// 初始化数据
onMounted(() => {
  fetchWarehouses()
  fetchInventoryList()
  fetchInventoryAlerts()
})

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const response = await getWarehouseList()
    warehouses.value = response.data
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  }
}

// 获取库存列表
const fetchInventoryList = async () => {
  loading.value = true
  try {
    const response = await getInventoryList(
      currentPage.value,
      pageSize.value,
      searchForm
    )
    inventoryList.value = response.data.items
    total.value = response.data.total
  } catch (error) {
    console.error('获取库存列表失败:', error)
    ElMessage.error('获取库存列表失败')
  } finally {
    loading.value = false
  }
}

// 获取库存预警
const fetchInventoryAlerts = async () => {
  try {
    const response = await getInventoryAlerts()
    alerts.value = response.data
  } catch (error) {
    console.error('获取库存预警失败:', error)
    ElMessage.error('获取库存预警失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchInventoryList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  fetchInventoryList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchInventoryList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchInventoryList()
}

// 查看详情
const viewDetails = async (row) => {
  try {
    const response = await getInventoryById(row.id)
    currentInventory.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取库存详情失败:', error)
    ElMessage.error('获取库存详情失败')
  }
}

// 查看交易记录
const viewTransactions = (row) => {
  currentInventoryId.value = row.id
  transactionCurrentPage.value = 1
  fetchInventoryTransactions()
  transactionDialogVisible.value = true
}

// 获取交易记录
const fetchInventoryTransactions = async () => {
  transactionLoading.value = true
  try {
    const response = await getInventoryTransactions(
      currentInventoryId.value,
      transactionCurrentPage.value,
      transactionPageSize.value
    )
    transactions.value = response.data.items
    transactionTotal.value = response.data.total
  } catch (error) {
    console.error('获取交易记录失败:', error)
    ElMessage.error('获取交易记录失败')
  } finally {
    transactionLoading.value = false
  }
}

// 交易记录分页大小变化
const handleTransactionSizeChange = (size) => {
  transactionPageSize.value = size
  fetchInventoryTransactions()
}

// 交易记录当前页变化
const handleTransactionCurrentChange = (current) => {
  transactionCurrentPage.value = current
  fetchInventoryTransactions()
}
</script>

<style scoped>
.inventory-management-container {
  padding: 20px;
}




.search-form {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.alert-warning {
  margin-bottom: 20px;
}

.alert-item {
  margin-top: 5px;
  padding-left: 10px;
  border-left: 3px solid #faad14;
}
</style>